package com.yaxin.outsourcing.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;

public class PdfToPrinter {

    public static void printPdf(File pdfFile) throws Exception {
        PDDocument document = PDDocument.load(pdfFile);
        PDFRenderer renderer = new PDFRenderer(document);

        // 渲染第一页为 BufferedImage
        BufferedImage image = renderer.renderImageWithDPI(0, 300);

        PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
        if (printService == null) {
            throw new RuntimeException("未找到默认打印机！");
        }

        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintService(printService);

        job.setPrintable(new Printable() {
            @Override
            public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
                if (pageIndex > 0) return NO_SUCH_PAGE;

                Graphics2D g2d = (Graphics2D) g;
                g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

                // 缩放适配
                double scaleX = pageFormat.getImageableWidth() / image.getWidth();
                double scaleY = pageFormat.getImageableHeight() / image.getHeight();
                double scale = Math.min(scaleX, scaleY);

                int newWidth = (int) (image.getWidth() * scale);
                int newHeight = (int) (image.getHeight() * scale);

                g2d.drawImage(image, 0, 0, newWidth, newHeight, null);
                return PAGE_EXISTS;
            }
        });

        job.print();
        document.close();
    }
}

